package com.koron.common.web.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.koron.common.bean.PubDepartmentBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.web.mapper.PubDepartmentNewMapper;
import com.koron.css2.common.utils.HttpUtils;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.ADOConnection;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.swan.bean.MessageBean;

import java.util.List;
import java.util.Map;

/**
 * 新的同步组织架构，从统一用户里面同步
 *
 * @author 陶梓洋
 * @date 2021年1月12日
 */
//@Component
public class SyncDepartmentNewTask {

    private static Logger log = LogManager.getLogger(SyncDepartmentNewTask.class);
    @Value("${app.syn_staff.param}")
    private String staffParam;
    @Value("${app.syn_orgNode.param}")
    private String orgNodeParam;
    @Value("${app.syn_org_url}")
    private String synOrgUrl;

    public MessageBean sync(SessionFactory factory) {
        try {
            syncDepartmentTask();
            syncStaffTask();
            return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "同步成功", Void.class);
        } catch (Exception e) {
            log.error("同步错误！", e);
        }
        return MessageBean.create(Constant.MESSAGE_INT_FAIL, "执行失败", Void.class);
    }


    // @Scheduled(cron = "0 0 22 * * ?") // 每天22点触发
    public void syncDepartmentTask() {
        log.info("同步组织架构开始！");
//        String s = HttpUtils.sendPostJson(synOrgUrl + "/port/orgNode.htm?org=" + org + "&root=" + root, "{\"data\":\"01\"}");
        String s = HttpUtils.sendPostJson(synOrgUrl + orgNodeParam, "{\"data\":\"01\"}");

        JsonNode jsonNode = JsonUtils.stringToJsonNode(s);
        System.out.println(jsonNode.get("data").toString());
        List<Map> departmentTreeBeans = JsonUtils.jsonToList(jsonNode.get("data").toString(), Map.class);
        ADOConnection.runTask(factory -> {
            try {
                PubDepartmentNewMapper mapper = factory.getMapper(PubDepartmentNewMapper.class);
                for (Map<String, Object> item : departmentTreeBeans) {
                    if (item.get("id") == null || "92433".equals(item.get("id"))) {
                        continue;
                    }
                    PubDepartmentBean dept = mapper.selectById(item.get("id").toString());
                    if (dept == null || dept.getId() == null) {  //若查找不到部门,则新建bean,防止Null
                        dept = new PubDepartmentBean();
                    }
                    dept.setName(item.get("name").toString());
                    dept.setShortName(item.get("shortName") == null ? "" : item.get("shortName").toString());
                    if (item.get("parentCode") == null) {
                        dept.setParentId(null);
                    } else {
                        PubDepartmentBean bean = mapper.selectSupId(item.get("parentCode").toString());
                        if (bean != null)
                            dept.setParentId(bean.getId());
                    }
                    dept.setSeq(Long.parseLong(item.get("seq").toString()));
                    dept.setCode(item.get("code").toString());
                    try {
                        if (dept.getId() == null) {
                            dept.setId(item.get("id").toString());
                            mapper.insert(dept);                    //插入部门
                        } else {
                            mapper.updateByPrimaryKeySelective(dept);   //更新部门信息
                        }
                    } catch (Exception e) {
                        log.error("插入或更新部门信息错误", e);
                        continue;
                    }
                }
                for (Map<String, Object> item : departmentTreeBeans) {  //更新父级id
                    if (item.get("id") == null) {
                        continue;
                    }
                    if (item.get("parentCode") != null) {
                        PubDepartmentBean dept = mapper.selectSupId(item.get("parentCode").toString());
                        if (dept != null && dept.getId() != null) {
                            mapper.updateParentId(dept.getId(), item.get("id").toString());
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                log.error("同步组织架构异常！", e);
            }
            return null;
        }, Void.class);
        log.info("同步组织架构结束！");
    }

    @Scheduled(cron = "0 0 22 * * ?") // 每天22点触发
//    @Scheduled(fixedRate = 1000 * 60 * 6000)
    public void syncStaffTask() {
        log.info("同步人员开始！");
        ADOConnection.runTask(factory -> {
//            String s = HttpUtils.sendPostJson(synOrgUrl + "/gdhk/staff.htm?org=" + org + "&root=" + root, "{\"data\":\"01\"}");
            String s = HttpUtils.sendPostJson(synOrgUrl + staffParam, "{\"data\":\"01\"}");
            JsonNode jsonNode = JsonUtils.stringToJsonNode(s);
            List<Map> list = JsonUtils.jsonToList(jsonNode.get("data").toString(), Map.class);
            PubDepartmentNewMapper mapper = factory.getMapper(PubDepartmentNewMapper.class);
            mapper.deleteAllStaff();
            Map curDept = null;
            int successCount = 0;
            int failCount = 0;
            for (Map<String, Object> item : list) {
                try {
                    StaffBean staff = mapper.selectByCode(item.get("code").toString());
                    if (staff == null) {
                        if (item.get("orgNodeCode") != null)
                            item.put("departmentCode", item.get("orgNodeCode").toString());
                        if (item.get("orgNodeName") != null)
                            item.put("departmentName", item.get("orgNodeName").toString());
                        item.put("position", null);
                        item.put("idcard", null);
                        if (item.get("loginName") != null)
                            item.put("loginid", item.get("loginName").toString());
                        if (item.get("weight") != null)
                            item.put("weighting", item.get("weight").toString());
                        item.put("photourl", null);
                        item.put("openId", null);
                        item.put("userid", null);
                        mapper.insertStaffByMap(item);
                        //System.out.println("插入成功1");
                        successCount++;
                    }
                } catch (Exception e) {
                    log.error("id=" + item.get("id").toString() + ",name=" + item.get("name") + " 的用户同步失败", e);
                    failCount++;
                }
            }
            log.info("成功同步用户人员数量:" + successCount);
            log.info("失败同步用户人员数量:" + failCount);
            return null;
        }, Void.class);
        log.info("同步人员结束！");
    }


}
